/*
 * Filename:    DrugStoreApproveServiceImpl.java
 * Copyright:   2015 中国平安保险（集团）股份有限公司 版权所有
 * Company:     平安科技养老险及健康险系统开发部
 * Create at:   2015-2-28
 */
package com.paic.mhis.hcpms.evaluation.evaluationDrugStore.drugStoreReview.biz.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.paic.mhis.core.auth.biz.service.UserDetails;
import com.paic.mhis.hcpms.evaluation.common.biz.service.EvaluationWorkFlowService;
import com.paic.mhis.hcpms.evaluation.common.constants.EvaluationConstants;
import com.paic.mhis.hcpms.evaluation.evaluationDrugStore.drugStoreReview.biz.service.DrugStoreApproveService;
import com.paic.mhis.hcpms.evaluation.evaluationOrg.evaluationIntegrity.constants.EvaluationOrgConstants;
import com.paic.mhis.hcpms.evaluation.evaluationOrg.evaluationIntegrity.dao.EvaluationOrgDao;
import com.paic.mhis.hcpms.evaluation.evaluationOrg.evaluationIntegrity.dto.EvalMarkDeatilInfoDTO;
import com.paic.mhis.hcpms.evaluation.evaluationOrg.evaluationIntegrity.dto.EvalMarkInfoDTO;
import com.paic.mhis.hcpms.evaluation.evaluationOrg.evaluationIntegrity.dto.EvalMarkUserComfirmDTO;
import com.paic.mhis.hcpms.evaluation.evaluationOrg.evaluationIntegrity.dto.EvaluationMarkContentDTO;
import com.paic.mhis.hcpms.evaluation.evaluationOrg.evaluationIntegrity.dto.IntegrityEvalDTO;
import com.paic.mhis.hcpms.evaluation.evaluationOrg.orgReview.constants.OrgReviewConstants;
import com.paic.mhis.hcpms.evaluation.evaluationOrg.orgReview.dao.OrgApproveDao;
import com.paic.mhis.hcpms.evaluation.evaluationOrg.orgReview.dao.OrgReviewDao;
import com.paic.mhis.hcpms.evaluation.evaluationOrg.orgReview.dto.MessageInfoDTO;
import com.paic.mhis.hcpms.evaluation.evaluationOrg.orgReview.dto.OrgEvaluationOpinionDTO;
import com.paic.mhis.hcpms.evaluation.evaluationOrg.orgReview.dto.OrgFinishConfirmDTO;
import com.paic.mhis.hcpms.evaluation.evaluationOrg.orgReview.dto.OrgReviewComfirmDTO;
import com.paic.mhis.hcpms.trust.common.ConstantsUtils;

@Component("DrugStoreApproveServiceImpl")
public class DrugStoreApproveServiceImpl implements DrugStoreApproveService {

	@Autowired
	private OrgApproveDao approveDao;

	@Autowired
	private OrgReviewDao orgReviewDao;
	@Autowired
	private EvaluationWorkFlowService evaluationWorkFlowService;
	@Autowired
	private EvaluationOrgDao evaluationOrgDao;

	/**
	 * 根据OrgEvaluationOpinionDTO 的流程状态和诚信考评字表的主键加载对应的意见信息
	 */
	@Override
	public OrgEvaluationOpinionDTO getEvaluatonOpinionDTO(OrgEvaluationOpinionDTO bean) {
		List<OrgEvaluationOpinionDTO> list = this.approveDao.getEvaluatonOpinionDTO(bean);
		if (list != null && list.size() > 0) {
			return list.get(0);
		} else {
			return null;
		}

	}

	/**
	 * // 首先判断当前的evalChildId是否已经做了保存，如果是则需要更新
	 * 
	 */
	@Transactional
	@Override
	public MessageInfoDTO processEvaluationApproveInfo(String evalChildId, String opinion, String opinionDesc,
			String evaluationCode, UserDetails user) throws Exception {

		MessageInfoDTO message = new MessageInfoDTO();

		OrgEvaluationOpinionDTO parameter = new OrgEvaluationOpinionDTO();

		parameter.setTaskStatus(OrgReviewConstants.eval_status_5);
		parameter.setIntgritEvalChildId(evalChildId);

		List<OrgEvaluationOpinionDTO> list = this.approveDao.getEvaluatonOpinionDTO(parameter);

		if (null != list && list.size() > 0) {
			for (OrgEvaluationOpinionDTO bean : list) {

				bean.setOpinion(opinion);
				bean.setOpertionUser(user.getUsername());
				bean.setOpinionDesc(opinionDesc);
				this.approveDao.updateOrgEvaluationOpinionDTO(bean);
			}
		} else {

			OrgEvaluationOpinionDTO saveBean = new OrgEvaluationOpinionDTO();
			saveBean.setIntgritEvalChildId(evalChildId);
			saveBean.setOpinion(opinion);
			saveBean.setOpinionDesc(opinionDesc);
			saveBean.setOpertionUser(user.getUsername());

			saveBean.setTaskStatus(OrgReviewConstants.eval_status_5);

			saveBean.setIsRevoke(OrgReviewConstants.IS_REVOKE_0);
			saveBean.setIsValid(OrgReviewConstants.is_valid_0);
			saveBean.setCreateUser(user.getUsername());
			saveBean.setUpdateUser(user.getUsername());
			this.approveDao.insertOrgEvaluationOpinionDTO(saveBean);
		}

		long evalCount = this.approveDao.getEvalInfoRecordById(evaluationCode);

		long opinionCountDisagree = this.approveDao.getEvaluationOpinionRecord(evaluationCode,
				OrgReviewConstants.opinion_0, OrgReviewConstants.eval_status_5, OrgReviewConstants.is_valid_0);

		long opinionCountAgress = this.approveDao.getEvaluationOpinionRecord(evaluationCode,
				OrgReviewConstants.opinion_1, OrgReviewConstants.eval_status_5, OrgReviewConstants.is_valid_0);

		if (evalCount == opinionCountDisagree) { // 不同意
			message.setFlag("true");

			// 不同意流程
			Map<String, String> conditionMap = new HashMap<String, String>();
			conditionMap.put(EvaluationConstants.EVALUATION_APPROVE_TYPE,
					EvaluationConstants.EVALUATION_APPROVE_TYPE_01);
			this.evaluationWorkFlowService.processWorkFlow(evaluationCode, user, conditionMap,
					EvaluationConstants.MODULE_TYPE_05);
			// 更新诚信考评状态为审批退回
			this.evaluationOrgDao.updateIntgrityEvalStatus(OrgReviewConstants.eval_status_4, user.getUsername(),
					evaluationCode);
			approveDao
					.reSetEvalOpinion(evaluationCode, OrgReviewConstants.eval_status_3, OrgReviewConstants.is_valid_0);
			approveDao
					.reSetEvalOpinion(evaluationCode, OrgReviewConstants.eval_status_5, OrgReviewConstants.is_valid_1);
		}

		if (evalCount == opinionCountAgress) { // 同意

			message.setFlag("true");

			// 同意流程
			Map<String, String> conditionMap = new HashMap<String, String>();
			conditionMap.put(EvaluationConstants.EVALUATION_APPROVE_TYPE,
					EvaluationConstants.EVALUATION_APPROVE_TYPE_02);
			this.evaluationWorkFlowService.processWorkFlow(evaluationCode, user, conditionMap,
					EvaluationConstants.MODULE_TYPE_05);

			// 更新诚信审批状态为完成
			this.evaluationOrgDao.updateIntgrityEvalStatus(OrgReviewConstants.eval_status_6, user.getUsername(),
					evaluationCode);

		}

		message.setSuccess("true");
		message.setMessage("success");

		return message;

	}

	/**
	 * 根据诚信考评主表的id 加载对应的考评信息
	 */
	@Override
	public List<OrgReviewComfirmDTO> processLoadEvalInfo(String evaluationCode, UserDetails user) {
		Date date = new Date();
		String processDate = ConstantsUtils.getDateFormateString(date);

		List<OrgReviewComfirmDTO> list = this.approveDao.queryOrgReviewComfirmDTOByEvalId(evaluationCode);
		if (list != null && list.size() > 0) {
			for (OrgReviewComfirmDTO bean : list) {
				bean.setOpertionUser(user.getDisplayName());
				bean.setOpertionDate(processDate);
			}
		}
		return list;

	}

	@Override
	public List<EvaluationMarkContentDTO> loadMarkContentDTOByRuleId(String ruleId, String evalChildId, UserDetails user) {

		List<EvaluationMarkContentDTO> contentList = this.orgReviewDao.queryEvaluationContentDTO(ruleId);

		List<EvaluationMarkContentDTO> markContentList = this.getContentList(contentList, evalChildId);

		return markContentList;
	}

	private List<EvaluationMarkContentDTO> getContentList(List<EvaluationMarkContentDTO> contentList, String evalChildId) {
		List<EvaluationMarkContentDTO> markContentList = new ArrayList<EvaluationMarkContentDTO>();
		if (contentList != null && contentList.size() > 0) {
			for (EvaluationMarkContentDTO contentBean : contentList) {

				String contentId = contentBean.getId();
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("evalChildId", evalChildId);
				map.put("evaluationInfoId", contentId);
				List<EvalMarkDeatilInfoDTO> markRuleList = this.orgReviewDao.queryEvaluationMarkRuleDTO(map);
				if (null != markRuleList && markRuleList.size() > 0) {
					List<EvalMarkDeatilInfoDTO> evalMarkDeatilInfoList = this
							.getMarkRuleList(markRuleList, evalChildId);
					contentBean.setList(evalMarkDeatilInfoList); // 设置考核内容下面的扣分细则
					markContentList.add(contentBean);
				}

			}
		}
		return markContentList;
	}

	private List<EvalMarkDeatilInfoDTO> getMarkRuleList(List<EvalMarkDeatilInfoDTO> markRuleList, String evalChildId) {
		List<EvalMarkDeatilInfoDTO> evalMarkDeatilInfoList = new ArrayList<EvalMarkDeatilInfoDTO>();
		if (markRuleList != null && markRuleList.size() > 0) {
			for (EvalMarkDeatilInfoDTO markRuleBean : markRuleList) {
				String markRuleId = markRuleBean.getId();
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("evalChildId", evalChildId);
				map.put("markRuleId", markRuleId);
				List<EvalMarkInfoDTO> markValueList = this.orgReviewDao.queryEvaluationMarkValueDTO(map);
				if (null != markValueList && markValueList.size() > 0) {
					markRuleBean.setList(markValueList); // 设置扣分细则下面的扣分值
					evalMarkDeatilInfoList.add(markRuleBean);
				} else {
					continue;
				}
				BigDecimal upperValue = markRuleBean.getUpperValue();
				BigDecimal lowerValue = markRuleBean.getLowerValue();
				if (upperValue != null && lowerValue != null) {
					markRuleBean.setMarkContent(markRuleBean.getMarkContent() + " " + lowerValue + "-" + upperValue
							+ "分");
				} else if (upperValue != null) {
					markRuleBean.setMarkContent(markRuleBean.getMarkContent() + " " + upperValue + "分");
				} else if (lowerValue != null) {
					markRuleBean.setMarkContent(markRuleBean.getMarkContent() + " " + lowerValue + "分");
				}
			}
		}
		return evalMarkDeatilInfoList;
	}

	@Override
	public IntegrityEvalDTO getIntegrityEvalDTOByTypeAndID(String evaluationCode, UserDetails user) {

		List<IntegrityEvalDTO> list = this.approveDao.loadIntegrityEvalDTOBy(
				EvaluationOrgConstants.EvaluationType_Drug, evaluationCode);

		if (null != list && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public List<OrgFinishConfirmDTO> loadEvaluationFinishInfo(String evaluationCode, UserDetails user) {

		List<OrgFinishConfirmDTO> returnList = new ArrayList<OrgFinishConfirmDTO>();

		List<OrgReviewComfirmDTO> list = this.approveDao.queryOrgReviewComfirmDTOByEvalId(evaluationCode);
		if (list != null && list.size() > 0) {
			for (OrgReviewComfirmDTO bean : list) {

				OrgFinishConfirmDTO target = new OrgFinishConfirmDTO();

				BeanUtils.copyProperties(bean, target);

				String evalChildId = bean.getIntgrityEvalChildId();
				OrgEvaluationOpinionDTO auditOpinion = new OrgEvaluationOpinionDTO();

				auditOpinion.setIntgritEvalChildId(evalChildId);

				auditOpinion.setTaskStatus(OrgReviewConstants.eval_status_3);
				List<OrgEvaluationOpinionDTO> auditList = this.approveDao.getEvaluatonOpinionDTO(auditOpinion);

				if (auditList != null && auditList.size() > 0) {

					OrgEvaluationOpinionDTO currentAuditOpinion = auditList.get(0);
					target.setAuditUser(currentAuditOpinion.getOpertionUser());
					target.setAuditDate(currentAuditOpinion.getOpertionDate());

				}

				auditOpinion.setTaskStatus(OrgReviewConstants.eval_status_5);
				List<OrgEvaluationOpinionDTO> approveList = this.approveDao.getEvaluatonOpinionDTO(auditOpinion);

				if (approveList != null && approveList.size() > 0) {

					OrgEvaluationOpinionDTO currentApproveOpinion = approveList.get(0);
					target.setApproveUser(currentApproveOpinion.getOpertionUser());
					target.setApproveDate(currentApproveOpinion.getOpertionDate());

				}

				returnList.add(target);

			}
		}
		return returnList;

	}

	@Transactional
	@Override
	public Map<String, Object> approveBatchSumit(String auditOpinion, String auditDesc, List<String> list,
			UserDetails user) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		for (String evaluationCode : list) {
			List<EvalMarkUserComfirmDTO> markUserDTOs = evaluationOrgDao.getEvalMarkUserComfirmInfo(evaluationCode);
			// 同意
			if (OrgReviewConstants.opinion_1.equals(auditOpinion)) {
				// 同意流程
				Map<String, String> conditionMap = new HashMap<String, String>();
				conditionMap.put(EvaluationConstants.EVALUATION_APPROVE_TYPE,
						EvaluationConstants.EVALUATION_APPROVE_TYPE_02);
				this.evaluationWorkFlowService.processWorkFlow(evaluationCode, user, conditionMap,
						EvaluationConstants.MODULE_TYPE_05);

				// 更新诚信审批状态为完成
				this.evaluationOrgDao.updateIntgrityEvalStatus(OrgReviewConstants.eval_status_6, user.getUsername(),
						evaluationCode);
				this.approvalOpinion(markUserDTOs, auditOpinion, auditDesc, user.getUsername());
			} else { // 不同意
				Map<String, String> conditionMap = new HashMap<String, String>();
				conditionMap.put(EvaluationConstants.EVALUATION_APPROVE_TYPE,
						EvaluationConstants.EVALUATION_APPROVE_TYPE_01);
				this.evaluationWorkFlowService.processWorkFlow(evaluationCode, user, conditionMap,
						EvaluationConstants.MODULE_TYPE_05);
				// 更新诚信考评状态为审批退回
				this.evaluationOrgDao.updateIntgrityEvalStatus(OrgReviewConstants.eval_status_4, user.getUsername(),
						evaluationCode);
				this.approvalOpinion(markUserDTOs, auditOpinion, auditDesc, user.getUsername());

				this.approveDao.reSetEvalOpinion(evaluationCode, OrgReviewConstants.eval_status_3,
						OrgReviewConstants.is_valid_0);

				this.approveDao.reSetEvalOpinion(evaluationCode, OrgReviewConstants.eval_status_5,
						OrgReviewConstants.is_valid_1);
			}
		}
		map.put(OrgReviewConstants.MSG_KEY, "审核完成!!!");
		map.put(OrgReviewConstants.STATE_KEY, OrgReviewConstants.SUCCESS_STATE_VALUE);
		return map;
	}

	// 审批同意
	private void approvalOpinion(List<EvalMarkUserComfirmDTO> markUserDTOs, String auditOpinion, String auditDesc,
			String userName) {
		for (EvalMarkUserComfirmDTO markUserDTO : markUserDTOs) {
			OrgEvaluationOpinionDTO opinionDto = new OrgEvaluationOpinionDTO();
			opinionDto.setTaskStatus(OrgReviewConstants.eval_status_5);
			opinionDto.setIntgritEvalChildId(markUserDTO.getIntgrityEvalChildId());
			// 判断是否撤回
			if (OrgReviewConstants.opinion_1.equals(auditOpinion)) {
				opinionDto.setIsRevoke(OrgReviewConstants.IS_REVOKE_0);
			} else {
				opinionDto.setIsRevoke(OrgReviewConstants.IS_REVOKE_1);
			}
			List<OrgEvaluationOpinionDTO> evaluationOpinionDTOs = approveDao.getEvaluatonOpinionDTO(opinionDto);
			// 判断 如果存在就更新批量的意见,不存在就新增意见
			if (null != evaluationOpinionDTOs && evaluationOpinionDTOs.size() > 0) {
				for (OrgEvaluationOpinionDTO bean : evaluationOpinionDTOs) {
					bean.setOpinion(auditOpinion);
					bean.setOpertionUser(userName);
					bean.setOpinionDesc(auditDesc);
					this.approveDao.updateOrgEvaluationOpinionDTO(bean);
				}
			} else {
				opinionDto.setOpinion(auditOpinion);
				opinionDto.setOpinionDesc(auditDesc);
				opinionDto.setOpertionUser(userName);
				opinionDto.setIsValid(OrgReviewConstants.is_valid_0);
				opinionDto.setCreateUser(userName);
				opinionDto.setUpdateUser(userName);
				this.approveDao.insertOrgEvaluationOpinionDTO(opinionDto);
			}
		}
	}

	/**
	 * 机构诚信审核岗对待审批的撤销
	 */
	@Transactional
	@Override
	public boolean cancelMedialIntegrityApprove(Map<String, Object> map) throws Exception {
		boolean flag = true;
		UserDetails user = (UserDetails) map.get("user");
		String evaluationCode = (String) map.get("evaluationCode");
		map.put("updatedBy", user.getUsername());
		map.put("evaluationCode", evaluationCode);
		map.put("status", OrgReviewConstants.eval_status_5);
		int count = approveDao.opinionCount(map);
		if (count > 0) {
			flag = false;
		} else {
			map.put("status", OrgReviewConstants.eval_status_3);
			// 更新状态
			this.approveDao.cancelMedialIntegrityApprove(map);
			// 撤销流程
			this.evaluationWorkFlowService.processWorkFlow(evaluationCode, user, user.getUsername(), null,
					EvaluationConstants.MODULE_TYPE_05, "N2015502");
		}
		return flag;
	}
}
